package com.example.concurrency.chapter6.lock;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class BlockingArrayList<E> {
    private ArrayList<E> arrayList = new ArrayList<>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    public void add(E e){
        writeLock.lock();
        try {
            arrayList.add(e);
        }finally {
            writeLock.unlock();
        }
    }

    public E get(int index){
        readLock.lock();
        try {
            return arrayList.get(index);
        }finally {
            readLock.unlock();
        }
    }
}
